#include<iostream>
#include<typeinfo>
#include<unistd.h>

class Any
{
private:
    class PlaceHolder
    {
    public:
        virtual ~PlaceHolder(){}
        virtual const std::type_info& type() = 0;
        virtual PlaceHolder* clone() = 0;

    };


    template<class T>
    class Holder : public PlaceHolder
    {
    public:
        ~Holder(){}
        Holder(const T& val):val_(val){}

        //返回的类型为：const std::type_info&
        const std::type_info& type(){return typeid(T);}

        PlaceHolder* clone(){return new Holder(val_);}
    public:
        T val_;
    };

    PlaceHolder* content_;
public:
    Any():content_(nullptr){}
    template<class T>
    Any(const T& val){content_ = new Holder<T>(val);}
    Any(const Any& other){
        content_ = other.content_->clone();
    }
    ~Any(){if(content_) delete content_;}

    template<class T>
    T* get(){
        if(typeid(T) != content_->type()){
            return nullptr;
        }

        return &((Holder<T>*)content_)->val_;
    }

    void swap(Any& other)
    {
        PlaceHolder* tmp = other.content_;
        other.content_ = content_;
        content_ = tmp;
    }

    template<class T>
    Any& operator=(const T& val){
        Any(val).swap(*this);
        return *this;
    }

    Any& operator=(const Any& other){
        Any(other).swap(*this);
        return *this;
    }
};


class Test
{
public:
    Test()
    {
        std::cout << "构造" << std::endl;

    }
    Test(const Test& t)
    {
        std::cout << "拷贝构造" << std::endl;
    }

    ~Test()
    {
        std::cout << "析构" << std::endl;

    }

};


int main()
{
    Any a;
    {
        Test t;
        a = t;
    }
    
    //a = 10;
    //int* tmp = a.get<int>();
    //std::cout << *tmp << std::endl;

    
    a = std::string("hahaha");
    std::string* tmp = a.get<std::string>();
    std::cout << *tmp << std::endl;
    // while(1)
    // {
    // }
    return 0;
}